//当前为用户信息仓库

import { defineStore } from "pinia";

import { ref, reactive } from "vue";

//引入请求函数
import { reqUserLogin } from "@/api/login/index.ts";
import { reqUserInfo } from "@/api/user/index.ts";
//引入vant轻提示
import { showSuccessToast, showFailToast } from "vant";

export const useUserStore = defineStore("userStore",() => {
    //用户token
    let token = ref("");
    //平台会员用户相关的信息
    const userInfo = reactive({
        id:0,
        username:"",
        password:"",
        nickname:"",
        email:"",
        phone:"",
        avatar:"",
        createTime:"",
        updateTime:""
    });

    //平台会员用户进行登录
    async function userLogin(userInfoForm){
        let res = await reqUserLogin (userInfoForm);
        console.log("前台会员用户登录api",res);
        if(res.code === 200) {
            token.value = res.result;
            localStorage.setItem("token",res.result);
            showSuccessToast("登录成功!");
            //获取用户信息
            let userinfo = "";
            if(userInfoForm.username !== ""){
                userinfo = userInfoForm.username;
                userInfo.username = userinfo;
            }
            if(userInfoForm.phone !== ""){
                userinfo = userInfoForm.phone;
                userInfo.phone = userinfo;
            }
            getUserInfo(userinfo);
            return true;  //返回布尔值
        } else {
            showFailToast(res.message);
            return false;
        }
    }

    //通过用户名或手机获取用户信息 userinfo:xiao0012|18296621863
    async function getUserInfo(userinfo:string) {
        let res = await reqUserInfo(userinfo);
        if(res.code === 200){
            //获取用户信息成功
            localStorage.setItem('userInfo',JSON.stringify(res.result));
            userInfo.id = res.result.id;
            userInfo.username = res.result.username;
            userInfo.password = res.result.password;
            userInfo.nickname = res.result.nickname;
            userInfo.email = res.result.email;
            userInfo.phone = res.result.phone;
            userInfo.avatar = res.result.avatar;
            //另存储一下用户名信息
            localStorage.setItem("username",res.result.username);
        }
        console.log('获取前台会员信息api',res);
    }

    return {
        userLogin,
        getUserInfo,
        userInfo,
        token
    }
})